package com.csun.dsms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.csun.dsms.comment.core.utils.wrapper.WrapMapper;
import com.csun.dsms.comment.core.utils.wrapper.Wrapper;
import com.csun.dsms.mapper.ProblemSummaryInfoMapper;
import com.csun.dsms.mapper.TicketProblemInfoMapper;
import com.csun.dsms.mapper.TicketProblemPercentMapper;
import com.csun.dsms.model.domain.TicketProblemPercent;
import com.csun.dsms.model.process.FileInfo;
import com.csun.dsms.model.process.LearnInfo;
import com.csun.dsms.model.process.ProblemSummaryInfo;
import com.csun.dsms.model.process.TicketProblemInfo;
import com.csun.dsms.model.vo.ticketproblem.TicketProblemPercentVo;
import com.csun.dsms.service.ProblemSummaryInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProblemSummaryInfoServiceImpl implements ProblemSummaryInfoService {

    @Resource
    private ProblemSummaryInfoMapper problemSummaryInfoMapper;

    @Resource
    private TicketProblemPercentMapper ticketProblemPercentMapper;

    @Resource
    private TicketProblemInfoMapper ticketProblemInfoMapper;

    @Override
    public Wrapper<Object> addProblemSummaryInfo(ProblemSummaryInfo problemSummaryInfo) {
        try {
            String prominentIssue = problemSummaryInfo.getProminentIssue();
            if (StrUtil.isBlank(prominentIssue)) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "突出问题不能为空");
            }
            ProblemSummaryInfo queryProblemSummaryInfo = new ProblemSummaryInfo();
            queryProblemSummaryInfo.setProminentIssue(prominentIssue);
            List<ProblemSummaryInfo> existProblemSummaryInfoList = problemSummaryInfoMapper.select(queryProblemSummaryInfo);
            if (CollectionUtil.isNotEmpty(existProblemSummaryInfoList)) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "突出问题已存在");
            }
            List<ProblemSummaryInfo> problemSummaryInfos = problemSummaryInfoMapper.selectAll();
            String formattedSequence = String.format("%02d", problemSummaryInfos.size()+1);
            problemSummaryInfo.setSummaryNo(DateUtil.format(new Date(), "yyMMdd") + formattedSequence);
            problemSummaryInfo.setCreatedTime(new Date());
            problemSummaryInfoMapper.insert(problemSummaryInfo);
            return WrapMapper.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> updateProblemSummaryInfo(ProblemSummaryInfo problemSummaryInfo) {
        try {
            Integer id = problemSummaryInfo.getId();
            if (id == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "id不能为空");
            }
            ProblemSummaryInfo existProblemSummaryInfo = problemSummaryInfoMapper.selectByPrimaryKey(id);
            if (existProblemSummaryInfo == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "突出问题不存在");
            }
            problemSummaryInfoMapper.updateByPrimaryKeySelective(problemSummaryInfo);
            return WrapMapper.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> deleteProblemSummaryInfo(ProblemSummaryInfo problemSummaryInfo) {
        try {
            Integer id = problemSummaryInfo.getId();
            if (id == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "id不能为空");
            }
            problemSummaryInfoMapper.deleteByPrimaryKey(id);
            return WrapMapper.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> selectProblemSummaryInfoPage(JSONObject reqJson) {
        try {
            DecimalFormat df = new DecimalFormat("0.00%");
            Integer pageSize = reqJson.getInteger("pageSize");
            Integer pageNum = reqJson.getInteger("pageNum");
            PageHelper.startPage(pageNum, pageSize);
            ProblemSummaryInfo problemSummaryInfo = new ProblemSummaryInfo();
            problemSummaryInfo.setProminentIssue(reqJson.getString("prominentIssue"));
            problemSummaryInfo.setLeadUnit(reqJson.getString("leadUnit"));
            problemSummaryInfo.setDataResource(reqJson.getString("dataResource"));
            problemSummaryInfo.setStatus(reqJson.getString("status"));
            List<ProblemSummaryInfo> problemSummaryInfoList = problemSummaryInfoMapper.selectByCondition(problemSummaryInfo);
            if(CollectionUtil.isNotEmpty(problemSummaryInfoList)){
                for (ProblemSummaryInfo summaryInfo : problemSummaryInfoList) {
                    List<Object> jsonDataList = CollectionUtil.newArrayList();
                    Integer id = summaryInfo.getId();
                    TicketProblemInfo queryTicketProblemInfo = new TicketProblemInfo();
                    queryTicketProblemInfo.setSummaryId(id);
                    List<TicketProblemInfo> ticketProblemInfoList = ticketProblemInfoMapper.select(queryTicketProblemInfo);
                    for (TicketProblemInfo ticketProblemInfo : ticketProblemInfoList) {
                        TicketProblemPercent ticketProblemPercentQuery = new TicketProblemPercent();
                        ticketProblemPercentQuery.setTicketProblemInfoId(ticketProblemInfo.getId());
                        List<TicketProblemPercent> ticketProblemPercentList = ticketProblemPercentMapper.select(ticketProblemPercentQuery);
                        List<TicketProblemPercentVo> ticketProblemPercentVoList = ticketProblemPercentList.stream().map(ticketProblemPercent -> {
                            TicketProblemPercentVo ticketProblemPercentVo = new TicketProblemPercentVo();
                            BeanUtils.copyProperties(ticketProblemPercent, ticketProblemPercentVo);
                            return ticketProblemPercentVo;
                        }).collect(Collectors.toList());
                        ticketProblemInfo.setTicketProblemPercentVoList(ticketProblemPercentVoList);
                    }
                    List<String> issueTypeList = ticketProblemInfoList.stream().map(TicketProblemInfo::getIssueType).distinct().filter(StrUtil::isNotBlank).collect(Collectors.toList());
                    for (String issueType : issueTypeList) {
                        List<JSONObject> valueList = CollectionUtil.newArrayList();
                        JSONObject jsonObject = new JSONObject();
                        JSONObject jsonObject1 = new JSONObject();
                        JSONObject jsonObject2 = new JSONObject();
                        JSONObject jsonObject3 = new JSONObject();
                        jsonObject.put("issueType", issueType);
                        List<TicketProblemInfo> issueTypeTicketProblemInfoList = ticketProblemInfoList.stream().filter(ticketProblemInfo -> issueType.equals(ticketProblemInfo.getIssueType())).collect(Collectors.toList());
                        int field1 = issueTypeTicketProblemInfoList.size();
                        long field2 = issueTypeTicketProblemInfoList.stream().filter(ticketProblemInfo -> ticketProblemInfo.getStatus() != null && !ticketProblemInfo.getStatus().equals("1")).count();
                        jsonObject1.put("name", "任务数");
                        jsonObject1.put("value", field1);
                        jsonObject2.put("name", "销号数");
                        jsonObject2.put("value", Convert.toInt(field2));
                        jsonObject3.put("name", "占比");
                        jsonObject3.put("value", Convert.toInt(field1) == 0 ? "0.00%" : df.format((double) Convert.toInt(field2)  / Convert.toInt(field1)) );
                        valueList.add(jsonObject1);
                        valueList.add(jsonObject2);
                        valueList.add(jsonObject3);
                        jsonObject.put("value", valueList);
                        jsonDataList.add(jsonObject);
                    }
                    summaryInfo.setJsonDataList(jsonDataList);
                }

            }
            Collections.sort(problemSummaryInfoList, Comparator.comparing(ProblemSummaryInfo::getId).reversed());
            return WrapMapper.ok(new PageInfo<>(problemSummaryInfoList));
        } catch (Exception e) {
            e.printStackTrace();
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> selectProblemSummaryInfoGroup(JSONObject reqJson) {
        try {
            DecimalFormat df = new DecimalFormat("0.00%");
            List<Object> resList = CollectionUtil.newArrayList();
            String group = reqJson.getString("group");

            List<ProblemSummaryInfo> problemSummaryInfoList = problemSummaryInfoMapper.selectAll();
            List<String> leadUnitList = problemSummaryInfoList.stream().map(ProblemSummaryInfo::getLeadUnit).distinct().filter(StrUtil::isNotBlank).collect(Collectors.toList());
            if ("leadUnit".equals(group)){
                for (String leadUnit : leadUnitList) {
                    JSONObject json = new JSONObject();
                    List<ProblemSummaryInfo> collect = problemSummaryInfoList.stream().filter(problemSummaryInfo -> problemSummaryInfo.getLeadUnit() != null && problemSummaryInfo.getLeadUnit().equals(leadUnit)).collect(Collectors.toList());
                    int field1 = collect.size();
                    long field2 = collect.stream()
                            .filter(problemSummaryInfo -> problemSummaryInfo.getStatus() != null && problemSummaryInfo.getStatus().equals("已销号")).count();
                    json.put("leadUnit",leadUnit);
                    json.put("field1",field1);
                    json.put("field2", Convert.toInt(field2));
                    json.put("field3", Convert.toInt(field1-Convert.toInt(field2)));
                    json.put("proportion",Convert.toInt(field1) == 0 ? "0.00%" : df.format((double) Convert.toInt(field2)  / Convert.toInt(field1)));
                    resList.add(json);
                }
            }
            return WrapMapper.ok(resList);
        } catch (Exception e) {
            e.printStackTrace();
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }
}
